package com.example.service.impl;

import com.common.utils.ThreadLocalUtil;
import com.example.exception.createException.DeletionNotAllowedException;
import com.example.mapper.CategoryMapper;
import com.example.mapper.DishMapper;
import com.example.service.CategoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pojo.dto.CategoryDTO;
import com.pojo.dto.QueryPageDTO;
import com.pojo.entity.Category;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper  dishMapper;




    @Override
    public Page<Category> page(QueryPageDTO queryPageDTO) {
        PageHelper.startPage(queryPageDTO.getPageNum(), queryPageDTO.getPageSize());
        Page<Category> page = categoryMapper.queryPage(queryPageDTO);
        return page;
    }

    @Override
    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
/*        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(ThreadLocalUtil.get());
        category.setUpdateUser(ThreadLocalUtil.get());*/
        categoryMapper.save(category);
    }

    @Override
    public void deleteById(Long id) throws DeletionNotAllowedException {
        Integer count = dishMapper.countByCategoryById(id);
        if (count > 0){
            throw new DeletionNotAllowedException("该分类下有菜品，不能删除");
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
/*        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(ThreadLocalUtil.get());*/
        categoryMapper.update(category);
    }

    @Override
    public Category getById(Long id) {
        return categoryMapper.getById(id);
    }

    @Override
    public List<Category> allList() {

        return categoryMapper.allList();
    }
}
